package com.pickme.food.service.impl;

import com.alibaba.fastjson.JSON;
import com.pickme.food.common.MC;
import com.pickme.food.common.exception.BusinessException;
import com.pickme.food.pojo.Orders;
import com.pickme.food.pojo.dto.OrdersDto;
import com.pickme.food.service.inte.OpenService;
import com.pickme.food.service.inte.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OpenServiceImpl implements OpenService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OrderService orderService;

    @Override
    public void cacheCurrentOrders(String key, OrdersDto dto) {
        HashOperations<String, String, String> operations = stringRedisTemplate.opsForHash();
        operations.put(key,dto.getNumber(),JSON.toJSONString(dto));
        stringRedisTemplate.expire(MC.KEY,2, TimeUnit.HOURS);
    }

    @Override
    public List<OrdersDto> listRecentOrders() {
        HashOperations<String, String, String> operations = stringRedisTemplate.opsForHash();
        List<String> values = operations.values(MC.KEY);
        //将value集合中每个json数据转换为对象返回
        return values.stream()
                .map(item -> JSON.parseObject(item, OrdersDto.class))
                .sorted((Comparator.comparing(OrdersDto::getCheckoutTime))) //排序
                .collect(Collectors.toList());
    }

    @Override
    public List<String> listRecentTakeCode() {
        HashOperations<String, String, String> operations = stringRedisTemplate.opsForHash();
        return operations.values(MC.KEY_TACK);
    }

    @Override
    public void updateOrdersToTake(String id) {
        HashOperations<String, String, String> operations = stringRedisTemplate.opsForHash();
        //删除hash中的key，即呼叫取餐的订单
        operations.delete(MC.KEY,id);
        //根据id查询订单信息
        Orders orders = orderService.getById(id);
        //缓存取餐码到待取餐
        String takeCode = orders.getTakeCode();
        operations.put(MC.KEY_TACK, takeCode,takeCode);
        stringRedisTemplate.expire(MC.KEY_TACK,2,TimeUnit.HOURS);
    }

    @Override
    public void removeTakeCode(String takeCode) {
        if (takeCode == null) throw new BusinessException(MC.E_UNKNOWN);
        stringRedisTemplate.opsForHash().delete(MC.KEY_TACK,takeCode);
        log.info("已取餐: {}",takeCode);
    }
}
